# -*- coding: utf-8 -*-

from sgmllib import SGMLParser, interesting, starttagopen, incomplete, entityref, charref, shorttagopen, shorttag, piclose, endbracket, tagfind, attrfind
import re
import urllib
from time import strptime, mktime
from datetime import datetime

from django.core.exceptions import ObjectDoesNotExist

from companyregister_exception import ObchodnyRegisterDetailException
from app.models import City, Address, Company_Type, Company, Company_Business, Person

class ObchodnyVestnikZoznamParser(SGMLParser):
	def __init__(self):
		SGMLParser.__init__(self)		
		self.last_issue_id = None

	def parse(self, content):
		self.feed(content)		
		self.close()		
		
	def get_last_issue_id(self):
		return self.last_issue_id
		
	def start_a(self, attrs):
		if not self.last_issue_id:
			for attr, value in attrs:
				if attr == 'href':
					if value.find('/PortalApp/ObchodnyVestnik/Web/Detail.aspx?IdOVod=') != -1:
						self.last_issue_id = get_number(value)
						break


class CompanyRegisterParser(SGMLParser):
	def __init__(self):
		SGMLParser.__init__(self)		
		self.cur_start_pos = 0
		self.cur_end_pos = 0
		self.amp_follows = False
		
		self.company_name = None
		self.company_address = ""
		
	def parse(self, content):
		self.feed(content)		
		self.close()		
				
	def goahead(self, end):
		rawdata = self.rawdata
		i = 0
		n = len(rawdata)
		while i < n:
			if self.nomoretags:
				self.handle_data(rawdata[i:n])
				i = n
				break
			match = interesting.search(rawdata, i)
			if match: j = match.start()
			else: j = n
			if i < j:
				self.cur_start_pos = i
				self.cur_end_pos = j
				self.amp_follows = (rawdata[j:j+1] == '&')
				self.handle_data(rawdata[i:j])
			i = j
			if i == n: break
			if rawdata[i] == '<':
				if starttagopen.match(rawdata, i):
					if self.literal:
						self.handle_data(rawdata[i])
						i = i+1
						continue
					k = self.parse_starttag(i)
					if k < 0: break
					i = k
					continue
				if rawdata.startswith("</", i):
					k = self.parse_endtag(i)
					if k < 0: break
					i = k
					self.literal = 0
					continue
				if self.literal:
					if n > (i + 1):
						self.handle_data("<")
						i = i+1
					else:
						# incomplete
						break
					continue
				if rawdata.startswith("<!--", i):
						# Strictly speaking, a comment is --.*--
						# within a declaration tag <!...>.
						# This should be removed,
						# and comments handled only in parse_declaration.
					k = self.parse_comment(i)
					if k < 0: break
					i = k
					continue
				if rawdata.startswith("<?", i):
					k = self.parse_pi(i)
					if k < 0: break
					i = i+k
					continue
				if rawdata.startswith("<!", i):
					# This is some sort of declaration; in "HTML as
					# deployed," this should only be the document type
					# declaration ("<!DOCTYPE html...>").
					k = self.parse_declaration(i)
					if k < 0: break
					i = k
					continue
			elif rawdata[i] == '&':
				if self.literal:
					self.handle_data(rawdata[i])
					i = i+1
					continue
				match = charref.match(rawdata, i)
				if match:
					name = match.group(1)
					self.handle_charref(name)
					i = match.end(0)
					if rawdata[i-1] != ';': i = i-1
					continue
				match = entityref.match(rawdata, i)
				if match:
					name = match.group(1)
					self.handle_entityref(name)
					i = match.end(0)
					if rawdata[i-1] != ';': i = i-1
					continue
			else:
				self.error('neither < nor & ??')
			# We get here only if incomplete matches but
			# nothing else
			match = incomplete.match(rawdata, i)
			if not match:
				self.handle_data(rawdata[i])
				i = i+1
				continue
			j = match.end(0)
			if j == n:
				break # Really incomplete
			self.handle_data(rawdata[i:j])
			i = j
		# end while
		if end and i < n:
			self.handle_data(rawdata[i:n])
			i = n
		self.rawdata = rawdata[i:]
		# XXX if end: check for empty stack

	def extend_data(self, data):
		ext_data = data
		if self.amp_follows:
			ext_end_pos = self.rawdata[self.cur_end_pos:].find('<')
			if ext_end_pos != -1:
				ext_data = self.rawdata[self.cur_start_pos:self.cur_end_pos + ext_end_pos]
		return ext_data
		
		
	def get_company(self):
		if not self.company_name:
			raise ObchodnyRegisterDetailException(u'Failed to create company, name is missing!')		
			
		try:
			self.company = Company.objects.get(name = self.company_name) #@UndefinedVariable
		except ObjectDoesNotExist:
			self.company = self.create_company(self.create_company_address(), self.create_company_type())				

		return self.company
		
		
	def create_company_address(self):
		address = None
		if self.company_address:
			#Jaseňová 10,  Bratislava 811 04,
			m = re.match("(.*?)\s(\d+.*?),(.*?)\s(\d+.*?),", self.company_address)
			if m:				
				try:
					city = None
					city_name = m.group(3).strip()
					try:
						city = City.objects.get(name = city_name)
					except ObjectDoesNotExist:
						city = City(name = city_name)
						city.save()
					address = Address.objects.get(street = m.group(1).strip(), number = m.group(2).strip()[:16], city = city, zip_code = m.group(4).strip()[:16]) #@UndefinedVariable
				except ObjectDoesNotExist:
					address = Address.objects.create(street = m.group(1).strip(), number = m.group(2).strip()[:16], city = city, zip_code = m.group(4).strip()[:16]) #@UndefinedVariable
			else:
				#Odbojárov 3,  Bratislava,					
				m = re.match("(.*?)\s(\d+.*?),(.*?),", self.company_address)
				if m:				
					try:
						city = None
						city_name = m.group(3).strip()
						try:
							city = City.objects.get(name = city_name)
						except ObjectDoesNotExist:
							city = City(name = city_name)
							city.save()						
						address = Address.objects.get(street = m.group(1).strip(), number = m.group(2).strip()[:16], city = city) #@UndefinedVariable
					except ObjectDoesNotExist:
						address = Address.objects.create(street = m.group(1).strip(), number = m.group(2).strip()[:16], city = city) #@UndefinedVariable
					
			if not address:
				raise ObchodnyRegisterDetailException(u'Failed to create company address  from "%s"!' % (self.company_address.encode('windows-1250', 'ignore')))
		else:
			raise ObchodnyRegisterDetailException(u'Failed to create company address, got empty data!')
		return address
		
		
	def create_company_type(self):
		company_type = None
		if self.company_type:			
			try:
				company_type = Company_Type.objects.get(type = self.company_type) #@UndefinedVariable
			except ObjectDoesNotExist:
				company_type = Company_Type.objects.create(type = self.company_type) #@UndefinedVariable
		else:
			raise ObchodnyRegisterDetailException(u'Failed to create company type, got empty data!')
		return company_type
		
	def create_company(self):
		raise NotImplementedError, "create_company() must be implemented by a derived class"
		


class ObchodnyVestnikDetailParser(CompanyRegisterParser):
	def __init__(self):
		CompanyRegisterParser.__init__(self)		
		self.new_company_list = []
		self.in_company_registry = False
		
	def get_new_company_list(self):
		return self.new_company_list
		
	def handle_data(self, data):
		if data.find(u'Obchodný register') != -1:
			self.in_company_registry = True
			return
		if data.find(u'Zbierka listín') != -1:
			self.in_company_registry = False
			return
			
		if self.in_company_registry and data.find(u'Podanie Obchodného registra Nové zápisy') != -1:
			data = self.extend_data(data)
			data = data.split('-')
			if len(data) == 3:
				self.new_company_list.append(data[2].strip().replace(';', ''))								
								
				
class ObchodnyRegisterCompanyZoznamParser(CompanyRegisterParser):
	def __init__(self, company):
		CompanyRegisterParser.__init__(self)
		self.company = company	
		self.company_link = None
		self.company_found = False
		
	def get_company_link(self):
		return self.company_link
		
	def start_a(self, attrs):
		if self.company_found and not self.company_link:
			for attr, value in attrs:
				if attr == 'href':
					if value.find('vypis.asp?ID=') != -1:
						self.company_link = "http://www.orsr.sk/%s" % value
						break
				
	def handle_data(self, data):
		data = data.strip()
		data = data.replace('\r\n', '')
		data = self.extend_data(data)
		if len(data) == 0:
			return			
		if data.find(self.company) != -1:
			self.company_found = True
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(self.company) != -1:
					self.company_found = True
			except Exception, e:
				pass
				
				
class ObchodnyRegisterPersonZoznamParser(CompanyRegisterParser):
	def __init__(self):
		CompanyRegisterParser.__init__(self)
		self.in_person_item = False
		self.column_num = -1
		self.person_name = None
		self.company_name = None
		self.company_person_list = []
		
	def get_company_person_list(self):
		return self.company_person_list
	
	def start_tr(self, attrs):
		if len(attrs) == 1:	
			for attr, value in attrs:
				if attr == 'bgcolor' and (value == '#EEEEEE' or value == '#DDDDDD'):
					self.in_person_item = True
					self.column_num = 1

	def end_tr(self):
		if self.in_person_item:
			self.in_person_item = False
			self.column_num = -1
			
	def start_a(self, attrs):	
		if self.in_person_item:
			for attr, value in attrs:
				if attr == 'href' and re.search('vypis.asp\?ID=(\d+)&SID=2&P=1$', value):					
					if self.person_name and self.company_name:
						self.company_person_list.append({'person_name': self.person_name, 
														'company_name': self.company_name,
														'company_link': value})
					
					break
																			
	def handle_data(self, data):
		data = data.strip()
		data = data.replace('\r\n', '')
		data = self.extend_data(data)
		if len(data) == 0:
			return					
		
		if self.in_person_item:
			if self.column_num == 2:
				self.person_name = data
			if self.column_num == 3:
				self.company_name = data
			self.column_num = self.column_num + 1
				
				
			
			
		
					
				
				
COMPANY_TYPE = {'sro': u'Spoločnosť s ručením obmedzeným',
				'ks': u'Komanditná spoločnosť',
				'as': u'Akciová spoločnosť',
				'spfo': u'Samostatne podnikajúca fyzická osoba'}				


class ObchodnyRegisterDetailFactoryParser(SGMLParser):
	def __init__(self, company_link):
		SGMLParser.__init__(self)	
		self.company_link = company_link
		self.in_company_type = False
		self.company_type = None
		
	def parse(self, content):		
		self.feed(content)		
		self.close()				
		
	def get_company_detail_parser(self):
		company_detail_parser = None
		if self.company_type:
			if self.company_type.find(COMPANY_TYPE['sro']) != -1:
				company_detail_parser = ObchodnyRegisterSroCompanyDetailParser(self.company_link)
			elif self.company_type.find(COMPANY_TYPE['ks']) != -1:
				company_detail_parser = ObchodnyRegisterKsCompanyDetailParser(self.company_link)
			elif self.company_type.find(COMPANY_TYPE['as']) != -1:
				company_detail_parser = ObchodnyRegisterAsCompanyDetailParser(self.company_link)
			elif self.company_type.find(COMPANY_TYPE['spfo']) != -1:
				company_detail_parser = ObchodnyRegisterSpfoCompanyDetailParser(self.company_link)																
			else:
				raise ObchodnyRegisterDetailException(u"Do not know how to parse details of a %s company (%s)" % (self.company_type, self.company_link))
		else:
			raise ObchodnyRegisterDetailException(u"Failed to obtain company type (%s)" % (self.company_link))
			
		return company_detail_parser
		

	def handle_data(self, data):
		data = data.strip()
		data = data.replace('\r\n', '')
		if len(data) == 0:
			return
			
		# company type
		if data.find(u'Právna forma') != -1:
			self.in_company_type = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Právna forma') != -1:
					self.in_company_type = True
					return
			except Exception, e:
				pass

		if self.in_company_type:
			self.company_type = data
			self.in_company_type = False
			return

			
class ObchodnyRegisterSroCompanyDetailParser(CompanyRegisterParser):
	def __init__(self, company_link):
		CompanyRegisterParser.__init__(self)
		self.company_link = company_link
		self.company = None
		self.in_company_name = False			
		self.in_company_address = False
		self.process_company_address = False		
		self.in_company_id = False
		self.company_id = None
		self.company_create_date = None
		self.in_company_create_date = False
		self.in_company_type = False
		self.company_type = COMPANY_TYPE['sro']
		self.in_company_business = False
		self.company_business = ""
		self.process_company_business = False
		self.in_company_management = False
		self.process_company_management = False
		self.company_management = ""
		self.company_management_links = {}
		self.in_company_management_link = False
		self.company_management_contact = ""
		self.company_management_link = None
				

	def parse(self, content):		
		self.feed(content)		
		self.close()		

						
	def create_company(self, address, company_type):
		company = None
		if not self.company_name:
			raise ObchodnyRegisterDetailException(u'Failed to create company, name is missing!')
		if not self.company_id:
			raise ObchodnyRegisterDetailException(u'Failed to create company, ICO is missing!')
		if not self.company_link:
			raise ObchodnyRegisterDetailException(u'Failed to create company, url is missing!')
		if not self.company_create_date:
			raise ObchodnyRegisterDetailException(u'Failed to create company, create date is missing!')		
		if not self.company_business:
			raise ObchodnyRegisterDetailException(u'Failed to create company, company business is missing!')
		if not self.company_management:							
			raise ObchodnyRegisterDetailException(u'Failed to create company, company management is missing!')
						
		try:
			company = Company.objects.get(name = self.company_name, address = address, company_id = self.company_id, company_type = company_type, url = self.company_link) #@UndefinedVariable
		except ObjectDoesNotExist:			
			created = datetime.fromtimestamp(mktime(strptime(self.company_create_date, '%d.%m.%Y')))
			if created:
				company = Company.objects.create(name = self.company_name, address = address, company_id = self.company_id, company_type = company_type, url = self.company_link, created = created) #@UndefinedVariable
			else:
				raise ObchodnyRegisterDetailException(u'Failed to create creation date from %s!' % created)
				
		if not company:
			raise ObchodnyRegisterDetailException(u'Failed to create company, reason unknown!')
		
		for business_item in self.company_business.split(';'):
			if not business_item:
				continue
			company_business = None
			try:
				company_business = Company_Business.objects.get(business = business_item) #@UndefinedVariable
			except ObjectDoesNotExist:
				company_business = Company_Business.objects.create(business = business_item, icon = '')			#@UndefinedVariable
			company.business_list.add(company_business)

		position = None
		for person_data in self.company_management.split(u'Vznik funkcie: %s,' % self.company_create_date):
			person = None
			address = None
			person_data = person_data.strip()
			if not person_data:
				continue
			#konateľ,  Juraj Štefanec,  216,  Tuchyňa 018 55,  
			m = re.match("(.*?),(.*?),(.*?)\s(\d+.*?),(.*?)\s(\d+.*?),", person_data)
			if m:	
				position = m.group(1)
				(title, first_name, last_name) = self.parse_person_name(m.group(2).strip())
				street = m.group(3).strip()
				street_number = m.group(4).strip()[:16]
				city_name = m.group(5).strip()
				zip_code = m.group(6).strip()[:16]
				
				city = None			
				try:
					city = City.objects.get(name = city_name)
				except ObjectDoesNotExist:
					city = City(name = city_name)
					city.save()						
																		
				try:
					address = Address.objects.get(street = street, number = street_number, city = city, zip_code = zip_code)					#@UndefinedVariable
				except ObjectDoesNotExist:
					address = Address.objects.create(street = street, number = street_number, city = city, zip_code = zip_code)					#@UndefinedVariable
				if not address:
					raise ObchodnyRegisterDetailException(u'Failed to create person address from "%s"!' % (person_data.encode('windows-1250', 'ignore')))
			else:
				#Juraj Štefanec,  216,  Tuchyňa 018 55,  
				m = re.match("(.*?),(.*?)\s(\d+.*?),(.*?)\s(\d+.*?),", person_data)		
				if m:		
					(title, first_name, last_name) = self.parse_person_name(m.group(1).strip())
					street = m.group(2).strip()
					street_number = m.group(3).strip()[:16]
					city_name = m.group(4).strip()
					zip_code = m.group(5).strip()[:16]						

					city = None			
					try:
						city = City.objects.get(name = city_name)
					except ObjectDoesNotExist:
						city = City(name = city_name)
						city.save()						
																			
					try:
						address = Address.objects.get(street = street, number = street_number, city = city, zip_code = zip_code)					#@UndefinedVariable
					except ObjectDoesNotExist:
						address = Address.objects.create(street = street, number = street_number, city = city, zip_code = zip_code) #@UndefinedVariable
				else:
					# konateľ,  Daniel Nižnan,  Modra 900 01,  Vznik funkcie: 14.04.2012, 
					m = re.match("(.*?),(.*?),(.*?)\s(\d+.*?),", person_data)
					if m:
						position = m.group(1)
						(title, first_name, last_name) = self.parse_person_name(m.group(2).strip())
						city_name = m.group(3).strip()
						zip_code = m.group(4).strip()[:16]						

						city = None			
						try:
							city = City.objects.get(name = city_name)
						except ObjectDoesNotExist:
							city = City(name = city_name)
							city.save()						

						try:
							address = Address.objects.get(city = city, zip_code = zip_code)					#@UndefinedVariable
						except ObjectDoesNotExist:
							address = Address.objects.create(city = city, zip_code = zip_code) #@UndefinedVariable
					else:
						# Daniel Nižnan,  Modra 900 01,  Vznik funkcie: 14.04.2012,
						m = re.match("(.*?),(.*?)\s(\d+.*?),", person_data)
						if m:
							(title, first_name, last_name) = self.parse_person_name(m.group(1).strip())
							city_name = m.group(2).strip()
							zip_code = m.group(3).strip()[:16]						
	
							city = None			
							try:
								city = City.objects.get(name = city_name)
							except ObjectDoesNotExist:
								city = City(name = city_name)
								city.save()						

							try:
								address = Address.objects.get(city = city, zip_code = zip_code)					#@UndefinedVariable
							except ObjectDoesNotExist:
								address = Address.objects.create(city = city, zip_code = zip_code) #@UndefinedVariable
						
			if not address:
				raise ObchodnyRegisterDetailException(u'Failed to create person address from "%s"!' % (person_data.encode('windows-1250', 'ignore')))
									
			try:
				person = Person.objects.get(position = position, title = title, first_name = first_name, last_name = last_name, address = address)					#@UndefinedVariable
			except ObjectDoesNotExist:
				person = Person.objects.create(position = position, title = title, first_name = first_name, last_name = last_name, address = address) #@UndefinedVariable
			if not person:
				raise ObchodnyRegisterDetailException(u'Failed to create person from "%s"!' % (person_data.encode('windows-1250', 'ignore')))
					
			company.person_list.add(person)
							
		return company
		
				
	def parse_person_name(self, name):		
		title = ''
		first_name = ''
		last_name = ''
		if name.find('-') != -1:
			name = name.split('-')[0].strip()
		name = name.split(' ')
		if len(name) == 2:
			first_name = name[0]
			last_name = name[1]
		else:
			title = ' '.join(name[:len(name) - 2])
			first_name = name[len(name) - 2]
			last_name = name[len(name) - 1]
		return (title, first_name, last_name)
				
				
								
	def start_td(self, attrs):
		if self.in_company_address:
			for attr, value in attrs:
				if attr == 'width' and value == '67%':
					self.process_company_address = True
					break
		if self.in_company_business:
			for attr, value in attrs:
				if attr == 'width' and value == '67%':
					self.process_company_business = True
					break
		if self.in_company_management:
			for attr, value in attrs:
				if attr == 'width' and value == '67%':
					self.process_company_management = True
					break
												
	def end_td(self):
		if self.process_company_address:
			self.process_company_address = False
			self.in_company_address = False
		if self.process_company_business:
			self.process_company_business = False
		if self.process_company_management:
			self.process_company_management = False
			
						
	def start_a(self, attrs):
		if self.in_company_management:
			for attr, value in attrs:
				if attr == 'href':
					url_startpos = self._SGMLParser__starttag_text.find('hladaj_osoba')
					if url_startpos != -1:	
						m = re.match(".*?PR=(.*?)&MENO=(.*?)&.*?", self._SGMLParser__starttag_text[url_startpos:])
						if m:
							self.company_management_link = "http://www.orsr.sk/hladaj_osoba.asp?PR=%s&MENO=%s&SID=0&T=f0&R=0" % (urllib.quote_plus(m.group(1).encode('windows-1250')),
																									urllib.quote_plus(m.group(2).encode('windows-1250'))) 
							self.in_company_management_link = True

									
	def end_a(self):
		if self.in_company_management_link:
			self.company_management_links[self.company_management_contact] = self.company_management_link
			self.in_company_management_link = False
			self.company_management_contact = ""
			
			
	def start_br(self, attrs):
		if self.process_company_address:
			self.company_address = "%s, " % self.company_address
		if self.process_company_management:
			self.company_management = "%s, " % self.company_management
									
	def handle_data(self, data):
		data = data.strip()
		data = data.replace('\r\n', '')
		data = self.extend_data(data)
		if len(data) == 0:
			return				
		
		# company_name
		if data.find(u'Obchodné meno') != -1:
			self.in_company_name = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Obchodné meno') != -1:
					self.in_company_name = True
					return
			except Exception, e:
				pass

		if self.in_company_name:
			self.company_name = data.strip()
			self.in_company_name = False
			return

		if data.find(u'Sídlo') != -1:
			self.in_company_address = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Sídlo') != -1:
					self.in_company_address = True
					return
			except Exception, e:
				pass

		# company_address
		if self.process_company_address:
			self.company_address = "%s %s" % (self.company_address, data)			
			return

		# company_id
		if data.find(u'IČO') != -1:
			self.in_company_id = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'IČO') != -1:
					self.in_company_id = True
					return
			except Exception, e:
				pass

		if self.in_company_id:
			self.company_id = data
			self.in_company_id = False
			return
	
		# company_create_date
		if data.find(u'Deň zápisu') != -1:
			self.in_company_create_date = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Deň zápisu') != -1:
					self.in_company_create_date = True
					return
			except Exception, e:
				pass

		if self.in_company_create_date:
			self.company_create_date = data
			self.in_company_create_date = False
			return
		
		# company business
		if data.find(u'Predmet činnosti') != -1:
			self.in_company_business = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Predmet činnosti') != -1:
					self.in_company_business = True
					return
			except Exception, e:
				pass

		if self.process_company_business:
			self.company_business = "%s;%s" % (self.company_business, data)			
			return

		if data.find(u'Spoločníci') != -1:
			self.in_company_business = False
			self.process_company_business = False
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Spoločníci') != -1:
					self.in_company_business = False
					self.process_company_business = False
					return
			except Exception, e:
				pass
						
	    # company management
		if data.find(u'Štatutárny orgán') != -1:
			self.in_company_business = False
			self.process_company_business = False
			self.in_company_management = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Štatutárny orgán') != -1:
					self.in_company_business = False
					self.process_company_business = False					
					self.in_company_management = True
					return					
			except Exception, e:
				pass
				
		if self.process_company_management:
			if self.in_company_management_link:
				self.company_management_contact = "%s %s" % (self.company_management_contact, data)
				
			self.company_management = "%s %s" % (self.company_management, data)			
			return				

		if data.find(u'Konanie menom spoločnosti') != -1:
			self.in_company_management = False
			self.process_company_management = False
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Konanie menom spoločnosti') != -1:
					self.in_company_management = False
					self.process_company_management = False
					return
			except Exception, e:
				pass


class ObchodnyRegisterKsCompanyDetailParser(ObchodnyRegisterSroCompanyDetailParser):
	def __init__(self, company_link):
		ObchodnyRegisterSroCompanyDetailParser.__init__(self, company_link)
		self.company_type = COMPANY_TYPE['ks']


class ObchodnyRegisterAsCompanyDetailParser(ObchodnyRegisterSroCompanyDetailParser):
	def __init__(self, company_link):
		ObchodnyRegisterSroCompanyDetailParser.__init__(self, company_link)
		self.company_type = COMPANY_TYPE['as']
		
	def create_company_management_link(self, company_contact_person_tokens):
		company_contact_person_lastname = None
		company_contact_person_firstname = None
		if len(company_contact_person_tokens) == 5:				
			company_contact_person_lastname = company_contact_person_tokens[2] 			
			company_contact_person_firstname = company_contact_person_tokens[1]
		elif len(company_contact_person_tokens) == 4:
			company_contact_person_lastname = company_contact_person_tokens[1] 			
			company_contact_person_firstname = company_contact_person_tokens[0]
		if company_contact_person_lastname and company_contact_person_firstname: 				
			self.company_management_link = "http://www.orsr.sk/hladaj_osoba.asp?PR=%s&MENO=%s&SID=0&T=f0&R=0" % (urllib.quote_plus(company_contact_person_lastname.encode('windows-1250')), 
				urllib.quote_plus(company_contact_person_firstname.encode('windows-1250')))
		
		
class ObchodnyRegisterSpfoCompanyDetailParser(CompanyRegisterParser):
	def __init__(self, company_link):
		CompanyRegisterParser.__init__(self)
		self.company_link = company_link
		self.company = None
		self.in_company_name = False			
		self.in_company_address = False
		self.process_company_address = False
		self.in_company_id = False
		self.company_id = None
		self.company_create_date = None
		self.in_company_create_date = False				
		self.in_company_type = False
		self.company_type = COMPANY_TYPE['spfo']
		self.in_company_business = False
		self.company_business = ""
		self.process_company_business = False

	def parse(self, content):		
		self.feed(content)		
		self.close()		
		
	def start_td(self, attrs):
		if self.in_company_address:
			for attr, value in attrs:
				if attr == 'width' and value == '67%':
					self.process_company_address = True
					break
		if self.in_company_business:
			for attr, value in attrs:
				if attr == 'width' and value == '67%':
					self.process_company_business = True
					break
												
	def end_td(self):
		if self.process_company_address:
			self.process_company_address = False
			self.in_company_address = False
		if self.process_company_business:
			self.process_company_business = False
									
	def start_br(self, attrs):
		if self.process_company_address:
			self.company_address = "%s, " % self.company_address
									
	def handle_data(self, data):
		data = data.strip()
		data = data.replace('\r\n', '')
		data = self.extend_data(data)
		if len(data) == 0:
			return				
		
		# company_name
		if data.find(u'Obchodné meno') != -1:
			self.in_company_name = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Obchodné meno') != -1:
					self.in_company_name = True
					return
			except Exception:
				pass

		if self.in_company_name:
			self.company_name = data.strip()
			self.in_company_name = False
			return

		if data.find(u'Miesto podnikania') != -1:
			self.in_company_address = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Miesto podnikania') != -1:
					self.in_company_address = True
					return
			except Exception:
				pass

		# company_address
		if self.process_company_address:
			self.company_address = "%s %s" % (self.company_address, data)			
			return

		# company_id
		if data.find(u'IČO') != -1:
			self.in_company_id = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'IČO') != -1:
					self.in_company_id = True
					return
			except Exception:
				pass

		if self.in_company_id:
			self.company_id = data
			self.in_company_id = False
			return
						
		# company_create_date
		if data.find(u'Deň zápisu') != -1:
			self.in_company_create_date = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Deň zápisu') != -1:
					self.in_company_create_date = True
					return
			except Exception:
				pass

		if self.in_company_create_date:
			self.company_create_date = data
			self.in_company_create_date = False
			return			
	
		# company business
		if data.find(u'Predmet činnosti') != -1:
			self.in_company_business = True
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Predmet činnosti') != -1:
					self.in_company_business = True
					return
			except Exception:
				pass

		if self.process_company_business:
			self.company_business = "%s;%s" % (self.company_business, data)			
			return

		if data.find(u'Dátum aktualizácie údajov') != -1:
			self.in_company_business = False
			self.process_company_business = False
			return
		else:
			try:
				data = data.decode('windows-1250')
				if data.find(u'Dátum aktualizácie údajov') != -1:
					self.in_company_business = False
					self.process_company_business = False
					return
			except Exception:
				pass
				
				
	def create_company(self, address, company_type):
		company = None
		if not self.company_name:
			raise ObchodnyRegisterDetailException(u'Failed to create company, name is missing!')
		if not self.company_id:
			raise ObchodnyRegisterDetailException(u'Failed to create company, ICO is missing!')
		if not self.company_link:
			raise ObchodnyRegisterDetailException(u'Failed to create company, url is missing!')
		if not self.company_create_date:
			raise ObchodnyRegisterDetailException(u'Failed to create company, create date is missing!')		
		if not self.company_business:
			raise ObchodnyRegisterDetailException(u'Failed to create company, company business is missing!')
						
		try:
			company = Company.objects.get(name = self.company_name, address = address, company_id = self.company_id, company_type = company_type, url = self.company_link) #@UndefinedVariable
		except ObjectDoesNotExist:			
			created = datetime.fromtimestamp(mktime(strptime(self.company_create_date, '%d.%m.%Y')))
			if created:
				company = Company.objects.create(name = self.company_name, address = address, company_id = self.company_id, company_type = company_type, url = self.company_link, created = created) #@UndefinedVariable
			else:
				raise ObchodnyRegisterDetailException(u'Failed to create creation date from %s!' % created)
				
		if not company:
			raise ObchodnyRegisterDetailException(u'Failed to create company, reason unknown!')
		
		for business_item in self.company_business.split(';'):
			if not business_item:
				continue
			company_business = None
			try:
				company_business = Company_Business.objects.get(business = business_item) #@UndefinedVariable
			except ObjectDoesNotExist:
				company_business = Company_Business.objects.create(business = business_item, icon = '')			#@UndefinedVariable
			company.business_list.add(company_business)
							
		return company
				
						


def get_number(url):
	rv = None
	m =  re.search('.*?(\d+)$', url)
	if m:
		rv = m.group(1)
	return rv
			
		

	
	
